package com.pine.service.pineframework.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.pine.common.beans.exception.BusinessException;
import com.pine.common.beans.exception.ExceptionCodeEnum;
import com.pine.common.beans.pineframework.request.SysUserQueryRequest;
import com.pine.common.beans.pineframework.response.SysUserCurrentInfoResponse;
import com.pine.common.beans.pineframework.response.SysUserQueryResponse;
import com.pine.common.beans.request.PageRequest;
import com.pine.common.beans.response.PageResponse;
import com.pine.common.util.user.UserInfo;
import com.pine.common.util.user.UserUtil;
import com.pine.dao.pineframework.entity.SysUser;
import com.pine.manager.core.SysUserInfo;
import com.pine.manager.pineframework.SysUserManager;
import com.pine.manager.pineframework.bo.SysUserBo;
import com.pine.manager.pineframework.convertors.SysUserConvertor;
import com.pine.manager.pineframework.query.SysUserQuery;
import com.pine.service.pineframework.SysUserService;
import com.pine.service.util.PageUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author pine manage
 * @since 2024-08-12
 */
@Slf4j
@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserManager sysUserManager;

    @Resource
    private SysUserConvertor sysUserConvertor;

    private static final Map<String, SFunction<SysUser, ?>> COLUMNS_FUNCTION_MAP;

    static {
        COLUMNS_FUNCTION_MAP = Map.of(
                "id", SysUser::getId
        );
    }



    /**
     * 通过唯一key查询单个数据
     *
     * @param uniqueKey 唯一键
     * @param column    列名
     * @return 单个数据查询响应结果
     */
    @Override
    public SysUserQueryResponse getOneByUniqueKey(Object uniqueKey, String column) {
        // 根据业务ID查询
        SysUserBo sysUserBo = sysUserManager.getOneByUniqueKey(uniqueKey, COLUMNS_FUNCTION_MAP.getOrDefault(column, SysUser::getId));
        return sysUserConvertor.entityBoToQueryResponse(sysUserBo);
    }

    /**
     * 查询信息（不分页）
     *
     * @param request 请求
     * @return 响应
     */
    @Override
    public List<SysUserQueryResponse> list(SysUserQueryRequest request) {
        SysUserQuery sysUserQuery = sysUserConvertor.queryRequestToQuery(request);
        if (ObjectUtils.isNotEmpty(sysUserQuery)) {
            List<SysUserBo> sysUserList = sysUserManager.list(sysUserQuery);
            if (ObjectUtils.isNotEmpty(sysUserList)) {
                return sysUserList.stream()
                        .map(sysUserConvertor::entityBoToQueryResponse)
                        .filter(ObjectUtils::isNotEmpty)
                        .collect(Collectors.toList());
            }
        }
        return Collections.emptyList();
    }


    /**
     * 查询信息（分页）
     *
     * @param request 请求
     * @return PageResponse 响应
     */
    @Override
    public PageResponse<SysUserQueryResponse> listPages(PageRequest<SysUserQueryRequest> request) {
        try {
            // 分页查询
            IPage<SysUserBo> sysUserPage = sysUserManager.page(transformToQuery(request));

            // 安全地处理分页转换逻辑
            return safelyConvertPage(sysUserPage);
        } catch (Exception e) {
            log.error("查询失败", e);
            throw new BusinessException(ExceptionCodeEnum.SELECT_ERROR);
        }
    }


    /**
     * 安全地将分页数据转换为响应对象
     *
     * @param sysUserPage 分页查询结果
     * @return 分页响应对象
     */
    private PageResponse<SysUserQueryResponse> safelyConvertPage(IPage<SysUserBo> sysUserPage) {
        if (sysUserPage == null || sysUserPage.getRecords() == null) {
            return new PageResponse<>();
        }

        // 使用并行流进行转换以提高效率，但需确保线程安全
        List<SysUserQueryResponse> responses = sysUserPage.getRecords().parallelStream()
                .map(sysUserBo -> sysUserConvertor.entityBoToQueryResponse(sysUserBo))
                .collect(Collectors.toList());

        return PageUtil.convertPage(sysUserPage, responses);
    }


    /**
     * 将请求 request 转换成 manager 的 query 对象
     *
     * @param request 请求参数
     * @return query 对象
     */
    private PageRequest<SysUserQuery> transformToQuery(PageRequest<SysUserQueryRequest> request) {
        SysUserQuery sysUserQuery = sysUserConvertor.queryRequestToQuery(request.getData());
        return new PageRequest<>(request.getPageNum(), request.getPageSize(), sysUserQuery);
    }

    /**
     * 获取当前用户信息
     *
     * @return 当前用户信息
     */
    @Override
    public SysUserCurrentInfoResponse getCurrentUserInfo() {
        UserInfo userInfo = UserUtil.get();
        if (ObjectUtils.isEmpty(userInfo)) {
            throw new BusinessException(ExceptionCodeEnum.USER_NOT_LOGIN);
        }
        SysUserInfo sysUserInfo = (SysUserInfo)userInfo;

        SysUserCurrentInfoResponse response = new SysUserCurrentInfoResponse();
        response.setId(sysUserInfo.getId());
        response.setLoginAccount(sysUserInfo.getLoginAccount());
        response.setUsername(sysUserInfo.getUsername());
        response.setAvatar(sysUserInfo.getAvatar());

        // 获取角色列表
        List<String> roleList = StpUtil.getRoleList();
        response.setRoles(roleList);
        // 获取权限列表
        List<String> permissionList = StpUtil.getPermissionList();
        response.setPermissions(permissionList);
        return response;
    }
}
